package com.jcark.arch.net

import com.jcark.arch.net.utils.AESOperator
import com.jcark.arch.net.utils.GsonParserUtils
import com.jcark.arch.net.utils.MD5Utils
import com.jcark.arch.net.utils.PackageUtils
import me.hgj.mvvm.base.Ktx

open class BaseRequestModel {
    // const val PLATFORM = 2 ////平台类型：1： 微信 ，2：Android ，3：iOS ，4：小程序
    private val APP_ID = NetConfigManager.INSTANCE.getAppId()
    private var platform: Int = 2
    private var version: String = ""
    private var timestamp: String = ""
    private var safeCode: String = ""
    private var netStatus: String = ""
    private var randomKey: String = ""
    private var data: String = ""
    private var sign: String = NetConfigManager.INSTANCE.getSign()
    private var token: String = NetConfigManager.INSTANCE.getToken()
    private var sysUpgrade: String? = null

    constructor(map: HashMap<String, Any>) {
        setData(map)
    }

    constructor(any: Any) {
        setData(GsonParserUtils.toHashMap(any))
    }

    constructor()

    init {
        val time = (System.currentTimeMillis().toString() + "").substring(0, 13)
        token = NetConfigManager.INSTANCE.getToken()
        val safeCodeTemp = time + APP_ID + token
        val sign1: String = MD5Utils.createSign(safeCodeTemp)
        version = PackageUtils.getPackageInfoByName(Ktx.app, Ktx.app.packageName)!!.versionName;
        timestamp = time
        safeCode = MD5Utils.MD5(sign1)
        netStatus = NetworkUtils.getAPNType(Ktx.app)
        sign = NetConfigManager.INSTANCE.getSign()
        sysUpgrade = if (NetConfigManager.INSTANCE.isUseSysUpgradeParam()) {
            NetConfigManager.INSTANCE.getSysUpgrade()
        } else {
            null
        }
    }

    /**
     * 设置参数
     * @param map HashMap<String, Any>
     */
    fun setData(map: HashMap<String, Any>) {
        val key: String = AESOperator.getInstance().KeyCreate(16)
        data = AESOperator.getInstance().encryptData(key, map)
        try {
            randomKey = AESOperator.getInstance().encrypt(key)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun toString(): String {
        return "BaseRequestViewModel{" +
                "platform=" + platform +
                ", version='" + version + '\'' +
                ", timestamp='" + timestamp + '\'' +
                ", safeCode='" + safeCode + '\'' +
                ", netStatus='" + netStatus + '\'' +
                ", randomKey='" + randomKey + '\'' +
                ", data='" + data + '\'' +
                ", sign='" + sign + '\'' +
                ", token='" + token + '\'' +
                getSysUpgradeParam() +
                '}'
    }

    private fun getSysUpgradeParam(): String {
        return if (NetConfigManager.INSTANCE.isUseSysUpgradeParam()) {
            ", sysUpgrade='" + NetConfigManager.INSTANCE.getSysUpgrade() + '\''
        } else {
            ""
        }
    }
}

